package com.ts.manager;

import android.app.Activity;
import android.content.ContentResolver;
import android.net.Uri;
import android.os.Handler;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.view.WindowManager;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.rio.core.U;
import com.rio.helper.json.G;
import com.rio.layout.LayoutManager;
import com.ts.api.BrightnessApi;
import com.ts.data.APIExecuteIMAction;
import com.ts.data.Instruct;
import com.ts.host.Event;

import de.greenrobot.event.EventBus;

public class BrightnessManager {

	private static final int DELYED = 10 * 60 * 60 * 1000;//10个小时后执行一次
	private static final int RADMON = 10 * 60 * 1000;//10分钟的随机数浮动
	
	private static BrightnessManager mBrightnessManager;
	
	private Handler handler = new Handler(); 
	
	public static BrightnessManager getInstance(){
		if(mBrightnessManager == null){
			mBrightnessManager = new BrightnessManager();
		}
		return mBrightnessManager;
	}

	public  void postDelay() {
		sendMessageDelayed();
	}
    
	private void sendMessageDelayed(){
        handler.postDelayed(runnable, U.getDownCountRandom(RADMON,DELYED));
	}
    
    
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // handler自带方法实现定时器
            try {
             	getActon();
             	sendMessageDelayed();
             } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };
	

	public  void getActon() {
		BrightnessApi api = new BrightnessApi();
		api.code = MachineManager.getInstance().getMachine().machinecode;
		HttpUtils http = new HttpUtils();
		http.send(HttpRequest.HttpMethod.GET, api.getRequest(),
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						// TODO Auto-generated method stub
						if (U.notNull(responseInfo)) {
							APIExecuteIMAction action = G.toObject(responseInfo.result, APIExecuteIMAction.class);
							if(U.notNull(action) && U.notNull(action.data) && !action.data.isEmpty()){
								Instruct in = action.data.get(0);
								if("2".equals(in.instructvalue)){
									EventBus.getDefault().post(new Event.ScreenBright());
								}
								if("1".equals(in.instructvalue)){
									EventBus.getDefault().post(new Event.ScreenDark());
								}
							}
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						
					}
				});

	}
	



	public  void setScreenBrightness(int brightness){
		Activity a = LayoutManager.getInstance().getActivity();
		if(U.notNull(a)){
	        ContentResolver resolver = a.getContentResolver();
			if(U.notNull(resolver) && isAutoBrightness(resolver)){
				stopAutoBrightness(resolver);
			}
			setBrightness(a,brightness);
		}
	}
	
	/**
	 * 判断是否开启了自动亮度调节
	 * 
	 * @param aContext
	 * @return
	 */
	private  boolean isAutoBrightness(ContentResolver aContentResolver) {
		boolean automicBrightness = false;
		try {
			automicBrightness = Settings.System.getInt(aContentResolver,
					Settings.System.SCREEN_BRIGHTNESS_MODE) == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
		} catch (SettingNotFoundException e) {
			e.printStackTrace();
		}
		return automicBrightness;
	}

	/**
	 * 获取屏幕的亮度
	 * 
	 * @param activity
	 * @return
	 */
	private  int getScreenBrightness(ContentResolver aContentResolver) {
		int nowBrightnessValue = 0;
		try {
			nowBrightnessValue = android.provider.Settings.System.getInt(
					aContentResolver, Settings.System.SCREEN_BRIGHTNESS);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return nowBrightnessValue;
	}

	/**
	 * 设置亮度
	 * 
	 * @param activity
	 * @param brightness
	 */
	private  void setBrightness(Activity activity, int brightness) {
		// Settings.System.putInt(activity.getContentResolver(),
		// Settings.System.SCREEN_BRIGHTNESS_MODE,
		// Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
		WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
		lp.screenBrightness = Float.valueOf(brightness) * (1f / 255f);
		activity.getWindow().setAttributes(lp);

	}

	/**
	 * 停止自动亮度调节
	 * 
	 * @param activity
	 */
	public  void stopAutoBrightness(ContentResolver aContentResolver) {
		Settings.System.putInt(aContentResolver,
				Settings.System.SCREEN_BRIGHTNESS_MODE,
				Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
	}

	/**
	 * 开启亮度自动调节
	 * 
	 * @param activity
	 */
	public  void startAutoBrightness(ContentResolver aContentResolver) {
		Settings.System.putInt(aContentResolver,
				Settings.System.SCREEN_BRIGHTNESS_MODE,
				Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
	}

	/**
	 * 保存亮度设置状态
	 * 
	 * @param resolver
	 * @param brightness
	 */
	private  void saveBrightness(ContentResolver resolver, int brightness) {
		Uri uri = android.provider.Settings.System
				.getUriFor("screen_brightness");
		android.provider.Settings.System.putInt(resolver, "screen_brightness",
				brightness);
		// resolver.registerContentObserver(uri, true, myContentObserver);
		resolver.notifyChange(uri, null);
	}
	
	public void destory(){
		if(handler != null){
			handler.removeCallbacksAndMessages(null);
		}
	}
}
